package com.sgb.kjwl.view.ui.activity.manage

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.google.android.material.tabs.TabLayout
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityTotalOrderBinding
import com.sgb.link.entity.PickFilterEntity
import com.sgb.link.utils.SizeUtils
import com.sgb.kjwl.view.ui.fragment.manage.*
import com.swgk.core.util.SharedPreferenceUtil
import java.lang.reflect.Field


/**
 * 代办 所有的订单
 */
class AgentTotalOrderActivity : AppActivity() {

    private var mTitles : ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Any>>>> ?= null
    private lateinit var mBinding : ActivityTotalOrderBinding
    private lateinit var mAdapter : TotalOrderPageAdapter
    private var mType :Int = 0//表示当前是企业1 个人0 团队2 组织3
    companion object{
        /**
         * titles 权限菜单 总共两级
         */
        const val KEY_DATAS = "key_datas"
        fun launch(context: Context, titles : ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Any>>>>?){
            val intent = Intent(context, AgentTotalOrderActivity::class.java)
            intent.putExtra(KEY_DATAS, titles)
            context.startActivity(intent)
        }
    }

    override fun initView() {
        super.initView()
        if (intent != null && intent.getSerializableExtra(KEY_DATAS) != null){
            mTitles = intent.getSerializableExtra(KEY_DATAS) as ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Any>>>>

        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_total_order)
        mType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0)
        if (mTitles == null || mTitles!!.isEmpty()){
            mBinding.emptyView.visibility = View.VISIBLE
            mBinding.llContent.visibility = View.GONE
        } else {
            mBinding.emptyView.visibility = View.GONE
            mBinding.llContent.visibility = View.VISIBLE
            mAdapter = TotalOrderPageAdapter(supportFragmentManager, mTitles!!,mType)
            mBinding.viewPage.adapter = mAdapter
            mBinding.viewPage.offscreenPageLimit = mTitles!!.size
            mBinding.tablayout.setupWithViewPager(mBinding.viewPage)
            mBinding.tablayout.tabMode = TabLayout.MODE_FIXED
            //initCustomize()
            mBinding.viewPage.currentItem = 0
        }
        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.include.titleView.text = "待办订单"
    }

    private fun initCustomize() {
        val total = mBinding.tablayout.tabCount
        var view : View ?= null
        for (i in 0..total){
            if (mBinding.tablayout.getTabAt(i) != null) {
                view = LayoutInflater.from(this).inflate(R.layout.item_tablayout_customize_view, null)
                val tvName = view.findViewById<TextView>(R.id.tvName)
                tvName.text = mTitles!![i].name
                val tvNum = view.findViewById<TextView>(R.id.tv_little_red_circle)
                tvNum.text = "".plus(if (mTitles!![i].num >= 99) "99+" else mTitles!![i].num)
                tvNum.visibility = if (mTitles!![i].num == 0) View.INVISIBLE else View.VISIBLE
                mBinding.tablayout.getTabAt(i)!!.customView = view
                setTabIndicator(view, mTitles!![i].num != 0, i, tvNum)
            }
        }


    }

    //通过反射设置指示器宽度
    private fun setTabIndicator(view : View?, isShowNum : Boolean, position: Int, viewNum: View?) {
        try {
            val mSlidingTabIndicator: Field = mBinding.tablayout::class.java.getDeclaredField("slidingTabIndicator")
            mSlidingTabIndicator.isAccessible = true
            val ltab  = mSlidingTabIndicator.get(mBinding.tablayout) as LinearLayout
            val intChildCount = ltab.childCount
            for(i in 0..intChildCount) {
                if (i == position) {
                    val childView = ltab.getChildAt(i)
                    val params = LinearLayout.LayoutParams(0, -1)

                    params.weight = 1f

                    params.leftMargin =
                        ((SizeUtils.getScreenWidth(this) - SizeUtils.dp2px(10f)) / 2 - SizeUtils.getMeasuredWidth(view)) / 2 - childView.paddingLeft - SizeUtils.dp2px(5f)

                    params.rightMargin =
                        ((SizeUtils.getScreenWidth(this) - SizeUtils.dp2px(10f)) / 2 - SizeUtils.getMeasuredWidth(view)) / 2 - childView.paddingRight - SizeUtils.dp2px(5f)
                    childView.layoutParams = params

                    childView.invalidate()
                }
            }
        } catch (e: Exception){

        }
    }

    class TotalOrderPageAdapter(fm : FragmentManager, titles : ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Any>>>>, type:Int) : FragmentPagerAdapter(fm) {
        private var mTitles : ArrayList<PickFilterEntity<ArrayList<PickFilterEntity<Any>>>> ?= null
        private var mType: Int = 0
        init {
            this.mTitles = titles
            this.mType = type
        }
        override fun getCount(): Int {
            if (mTitles != null){
                return mTitles!!.size
            }
            return 0
        }

        override fun getItem(position: Int): Fragment {
            var no = mTitles!![position].no
            when(no) {
                "1" -> { //商品订单
                    return AgentGoodsOrderFragment.newInstance(mTitles!![position].children)
                }
                "2" -> { //租赁订单
                    return AgentLeaseOrderFragment.newInstance(mTitles!![position].children)
                }
                "3" -> { //物流订单--货主 待确定、待付款 1,3
                    if (mType == 0){
                        return LogisticsTransportOrderFragment.newInstance()
                    } else if (mType == 1){
                        return AgentTransportOrderOwnerFragment.newInstance()
                    }
                      //  return AgentTransportOrderOwnerFragment.newInstance()
                }
                "4" -> { //服务订单
                    return OtherInquiryFragment.newInstance()
                }
            }
            return OtherInquiryFragment.newInstance()
        }

        override fun getPageTitle(position: Int): CharSequence {
            if (mTitles != null){
                return mTitles!![position].name
            }
            return ""
        }
    }
}